/*
package com.thread.threadfirst.http.loan.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fugui.marvel.common.constants.CommonConstants;
import com.fugui.marvel.common.dto.Page;
import com.fugui.marvel.common.enums.*;
import com.fugui.marvel.common.utils.OrderNoUtil;
import com.fugui.marvel.common.utils.QrCodeUtil;
import com.fugui.marvel.common.utils.RsaUtils;
import com.fugui.marvel.common.utils.UpdateTool;
import com.fugui.marvel.common.utils.httpclient.HttpClient;
import com.fugui.marvel.service.common.domain.loan.TIntegralChannel;
import com.fugui.marvel.service.common.domain.loan.TIntegralOrder;
import com.fugui.marvel.service.common.domain.user.TUser;
import com.fugui.marvel.service.common.dto.ReturnT;
import com.fugui.marvel.service.common.dto.loan.IntegralCategory;
import com.fugui.marvel.service.common.dto.loan.IntegralCategoryPrice;
import com.fugui.marvel.service.common.form.profitform.ProfitThreeForm;
import com.fugui.marvel.service.common.repository.loan.IntegralChannelRepository;
import com.fugui.marvel.service.common.repository.loan.IntegralOrderlRepository;
import com.fugui.marvel.service.common.service.fastdfs.UploadService;
import com.fugui.marvel.service.common.service.feign.client.loan.FeignIntegralServiceClient;
import com.fugui.marvel.service.common.service.feign.client.payment.FeignProfitTaskServiceClient;
import com.fugui.marvel.service.common.service.feign.client.user.FeignUserAccountServiceClient;
import com.fugui.marvel.service.common.service.feign.client.user.FeignUserServiceClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

*/
/**
 * @author saving
 * @date 2019/08/16
 * @description 积分服务
 *//*

@Service
@RestController
@Api(value = "积分接口服务", tags = "积分接口服务")
@RefreshScope
public class IntegralServiceImpl implements FeignIntegralServiceClient {

    Logger logger = LoggerFactory.getLogger(IntegralServiceImpl.class);
    */
/**
     * 生产地址
     *//*

    @Value(value = "${weiqiatong.baseHost}")
    private String baseHost;

    */
/**
     * 站点id
     *//*

    @Value(value = "${weiqiatong.oemID}")
    private String oemID;

    */
/**
     * 商户号
     *//*

    @Value(value = "${weiqiatong.merchant}")
    private String merchant;

    */
/**
     * 公钥
     *//*

    @Value(value = "${weiqiatong.publicKey}")
    private String publicKey;

    */
/**
     * 私钥
     *//*

    @Value(value = "${weiqiatong.privateKey}")
    private String privateKey;

    @Value(value = "${weiqiatong.callbackIntegralUrl}")
    private String callbackIntegralUrl;

    @Value("${fastdfs.base.url}")
    private String FASTDFS_BASE_URL;
    @Value(value = "${loan.platform.profitPercent}")
    private String profitPercent;

    @Autowired
    private FeignUserServiceClient feignUserServiceClient;

    @Autowired
    private IntegralChannelRepository integralChannelRepository;

    @Autowired
    private IntegralOrderlRepository integralOrderlRepository;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private FeignProfitTaskServiceClient feignProfitTaskServiceClient;

    @Autowired
    private FeignUserAccountServiceClient feignUserAccountServiceClient;

    @Override
    @ApiOperation(value = "同步第三方积分通道接口")
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getBankListFromThird")
    public ReturnT getIntegralListFromThird() {
        String url = baseHost + "/conversion/open/channel/list";
        // 生成时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 公钥加密
        String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
        // 建立请求头部数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("X-Auth-OEM", oemID);
        baseMap.put("X-Open-Sign", sign);
        baseMap.put("X-Open-Merchant", merchant);
        baseMap.put("X-Open-Timestamp", timestamp);

        logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步积分解析结果=" + RsaUtils.decrypt(privateKey, sign));
        // 建立GET请求
        String resultText = HttpClient.doGet(url, baseMap);

        logger.info("积分同步通道resultText={}" + resultText);

        JSONObject object = null;
        try {
            object = JSONObject.parseObject(resultText);
        } catch (Exception e) {
            logger.error("getIntegralListFromThird JSONObject parseObject error");
        }
        if (object == null) {
            return new ReturnT("resultText为空");
        }
        List<String> channelList = new ArrayList<>();
        if (object.containsKey("status")) {
            String status = object.getString("status");
            if (CommonConstants.LEY_RESULT_SUCCESS.equals(status)) {
                JSONArray array = JSONArray.parseArray(object.getString("result"));
                for (int i = 0; i < array.size(); i++) {
                    String channelId = array.getJSONObject(i).getString("id");
                    String customerServiceUrlPath = array.getJSONObject(i).getString("customerServiceUrlPath");
                    String enable = array.getJSONObject(i).getString("enable");
                    String isCustomerService = array.getJSONObject(i).getString("customerService");

                    String platformChannelName = array.getJSONObject(i).getJSONObject("platformChannel").getString("name");
                    String platformChannelId = array.getJSONObject(i).getJSONObject("platformChannel").getString("id");
                    String platformChannelType = array.getJSONObject(i).getJSONObject("platformChannel").getString("type");
                    BigDecimal platformChannelMinPrice = new BigDecimal(array.getJSONObject(i).getJSONObject("platformChannel").getString("minPrice"));
                    String platformProductId = array.getJSONObject(i).getJSONObject("platformProduct").getString("id");
                    String platformProductName = array.getJSONObject(i).getJSONObject("platformProduct").getString("name");

                    Integer sort = array.getJSONObject(i).getInteger("sort");

                    TIntegralChannel integralChannel = new TIntegralChannel();
                    integralChannel.setChannelId(channelId);
                    integralChannel.setCustomerServiceUrlPath(customerServiceUrlPath);
                    integralChannel.setPlatformChannelName(platformChannelName);
                    integralChannel.setPlatformChannelId(platformChannelId);
                    integralChannel.setPlatformChannelType(platformChannelType);
                    integralChannel.setPlatformChannelMinPrice(platformChannelMinPrice);
                    integralChannel.setPlatformProductId(platformProductId);
                    integralChannel.setPlatformProductName(platformProductName);
                    integralChannel.setIsCustomerService(isCustomerService);

                    Integer thirdStatus = 0;
                    if ("ACTIVATE".equalsIgnoreCase(enable)) {
                        thirdStatus = 1;
                    }
                    integralChannel.setThridStatus(thirdStatus);
                    integralChannel.setSort(sort);
                    integralChannel.setStatus(ChannelStatusTypeEnum.TYPE_DOWN.getKey());

                    TIntegralChannel channel = integralChannelRepository.queryTIntegralChannelByChannelId(channelId);
                    if (channel != null) {
                        integralChannel.setId(channel.getId());
                        integralChannel.setUpdateTime(new Date());
                        UpdateTool.copyProperties(channel, integralChannel);
                    } else {
                        integralChannel.setCreateTime(new Date());
                    }

                    integralChannel.setMarketId(MarketTypeEnum.TYPE_WECHARTTONG.getKey());
                    integralChannel.setIsHot(0);
                    integralChannelRepository.saveAndFlush(integralChannel);
                    channelList.add(channelId);
                }
            }
        } else {
            logger.error("getIntegralListFromThird return data execption resultText={}", resultText);
        }
        if (channelList != null && channelList.size() > 0) {
            integralChannelRepository.updateTIntegralChannelByChannelId(channelList);
        }
        logger.info("积分同步通道完成");
        return new ReturnT(ReturnT.SUCCESS_CODE,"同步成功");

    }

    @Override
    @ApiOperation(value = "获取通道类目接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "channelId", value = "通道channel标示", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "platformChannelId", value = "platformChannelId标示", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前系统用户标示", dataType = "long", required = true, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getIntegralCategoryFromThird")
    public List<IntegralCategory> getIntegralCategoryFromThird(@RequestParam(value = "channelId", required = true) String channelId,
                                                               @RequestParam(value = "platformChannelId", required = true) String platformChannelId,
                                                               @RequestParam(value = "userId", required = true) Long userId) {
        {
            String url = baseHost + "/conversion/open/channel/tags";
            // 生成时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            // 公钥加密
            String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
            // 建立请求头部数据
            Map<String, String> baseMap = new HashMap<>();
            baseMap.put("X-Auth-OEM", oemID);
            baseMap.put("X-Open-Sign", sign);
            baseMap.put("X-Open-Merchant", merchant);
            baseMap.put("X-Open-Timestamp", timestamp);

            logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步类目解析结果=" + RsaUtils.decrypt(privateKey, sign));
            Map<String, String> param = new HashMap<>();
            param.put("channelId", platformChannelId);
            param.put("onlyNo", String.valueOf(userId));
            // 建立GET请求
            String resultText = HttpClient.doGet(url, baseMap, param);

            logger.info("类目同步resultText={}" + resultText);

            JSONObject object = null;
            try {
                object = JSONObject.parseObject(resultText);
            } catch (Exception e) {
                logger.error("getIntegralCategoryFromThird JSONObject parseObject error");
            }
            List<IntegralCategory> list = new ArrayList<>();
            if (object == null) {
                return list;
            }
            List<String> channelList = new ArrayList<>();
            if (object.containsKey("status")) {
                String status = object.getString("status");
                if (CommonConstants.LEY_RESULT_SUCCESS.equals(status)) {
                    IntegralCategoryPrice categoryPriceFromThird = getCategoryPriceFromThird(channelId);
                    JSONArray array = JSONArray.parseArray(object.getString("result"));
                    for (int i = 0; i < array.size(); i++) {
                        String id = array.getJSONObject(i).getString("id");//类目id
                        String title = array.getJSONObject(i).getString("title");//标题
                        String remark = array.getJSONObject(i).getString("remark");//操作流程
                        String credit = array.getJSONObject(i).getString("credit");//该兑换商品需要积分数
                        String conversionCount = array.getJSONObject(i).getString("conversionCount");//每月支持兑换数
                        String customerServiceUrl = array.getJSONObject(i).getString("customerServiceUrl");//客服链接，直接从定向地址，在result最外层
                        logger.info("title={},remark={},credit={},conversionCount={},customerServiceUrl={}", title, remark, credit, conversionCount, customerServiceUrl);

                        IntegralCategory category = new IntegralCategory();
                        category.setCategotyId(id);
                        category.setTitle(title);
                        category.setRemark(remark);
                        category.setCredit(credit);
                        if (Integer.parseInt(conversionCount)==0) {
                            category.setConversionCount("不限制");
                        }else {
                            category.setConversionCount(conversionCount);
                        }
                        category.setCustomerServiceUrl(customerServiceUrl);

                        if (categoryPriceFromThird != null) {
                            category.setPrice(categoryPriceFromThird.getPrice());
                            category.setCategotyPrice(new BigDecimal(category.getCredit()).divide(new BigDecimal("10000"))
                                    .multiply(new BigDecimal(categoryPriceFromThird.getPrice())).divide(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_DOWN));
                        }
                        list.add(category);
                    }
                }
            } else {
                logger.error("getIntegralCategoryFromThird return data execption resultText={}", resultText);
            }
            logger.info("类目同步获取完成");
            return list;
        }
    }

    @Override
    @ApiOperation(value = "获取通道价格接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "channelId", value = "通道channel标示", dataType = "string", required = true, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getCategoryPriceFromThird")
    public IntegralCategoryPrice getCategoryPriceFromThird(@RequestParam(value = "channelId", required = true) String channelId) {
        {
            String url = baseHost + "/conversion/open/channel/price/" + channelId;
            // 生成时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            // 公钥加密
            String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
            // 建立请求头部数据
            Map<String, String> baseMap = new HashMap<>();
            baseMap.put("X-Auth-OEM", oemID);
            baseMap.put("X-Open-Sign", sign);
            baseMap.put("X-Open-Merchant", merchant);
            baseMap.put("X-Open-Timestamp", timestamp);

            logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步类目价格解析结果=" + RsaUtils.decrypt(privateKey, sign));
            // 建立GET请求
            String resultText = HttpClient.doGet(url, baseMap, null);

            logger.info("类目价格同步resultText={}" + resultText);

            JSONObject object = null;
            try {
                object = JSONObject.parseObject(resultText);
            } catch (Exception e) {
                logger.error("getCategoryPriceFromThird JSONObject parseObject error");
            }
            IntegralCategoryPrice categoryPrice = new IntegralCategoryPrice();
            if (object == null) {
                return categoryPrice;
            }
            List<String> channelList = new ArrayList<>();
            if (object.containsKey("status")) {
                String status = object.getString("status");
                if (CommonConstants.LEY_RESULT_SUCCESS.equals(status)) {
                    String result = object.getString("result");
                    String name = JSONObject.parseObject(result).getString("name"); //通道名称
                    String id = JSONObject.parseObject(result).getString("id"); //通道id
                    String price = JSONObject.parseObject(result).getString("price"); //通道价格
                    String description = JSONObject.parseObject(result).getString("description"); //通道描述
                    categoryPrice.setName(name);
                    categoryPrice.setId(id);
                    categoryPrice.setDescription(description);
                    categoryPrice.setPrice(price);
                }
            } else {
                logger.error("getIntegralCategoryFromThird return data execption resultText={}", resultText);
            }
            logger.info("类目价格同步获取完成");
            return categoryPrice;
        }
    }

    @Override
    @ApiOperation(value = "获取通道类目操作流程接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categotyId", value = "类目标示", dataType = "string", required = true, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getCategoryProcessFromThird")
    public String getCategoryProcessFromThird(@RequestParam(value = "categotyId", required = true) String categotyId) {
        {
//            String url = baseHost + "/recommend/excDetail.html?id=" + categotyId;
            String url = "https://lion.51ley.com/recommend/excDetail.html?id=" + categotyId;
            // 生成时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            // 公钥加密
            String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
            // 建立请求头部数据
            Map<String, String> baseMap = new HashMap<>();
            baseMap.put("X-Auth-OEM", oemID);
            baseMap.put("X-Open-Sign", sign);
            baseMap.put("X-Open-Merchant", merchant);
            baseMap.put("X-Open-Timestamp", timestamp);

            logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步类目价格解析结果=" + RsaUtils.decrypt(privateKey, sign));
            // 建立GET请求
            String resultText = HttpClient.doGet(url, baseMap, null);
//            resultText=resultText.substring(resultText.indexOf("<body>")+7,resultText.lastIndexOf("</body>"));
            return resultText;
        }
    }

    @Override
    @ApiOperation(value = "短信报单流程接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "smsCode", value = "第三方短信验证码", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "orderId", value = "订单标示", dataType = "int", required = true, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/saveIntegralOrderPhoneToThird")
    public Map<String, Object> saveIntegralOrderPhoneToThird(@RequestParam(value = "smsCode", required=true) String smsCode,
                                                      @RequestParam(value = "orderId", required=true) Integer orderId){
        String url = baseHost + "/conversion/open/channel/wemSetSms";
        // 生成时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 公钥加密
        String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
        // 建立请求头部数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("X-Auth-OEM", oemID);
        baseMap.put("X-Open-Sign", sign);
        baseMap.put("X-Open-Merchant", merchant);
        baseMap.put("X-Open-Timestamp", timestamp);

        logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步类目价格解析结果=" + RsaUtils.decrypt(privateKey, sign));
        // 建立POST请求
        Optional<TIntegralOrder> option = integralOrderlRepository.findById(orderId);
        TIntegralOrder order = option.isPresent() ? option.get() : null;
        if(order == null) {
            throw new RuntimeException("参数异常");
        }
        Map<String,String> bodyMap = new HashMap<>();
        bodyMap.put("oemChannelId",order.getChannelId());
        bodyMap.put("clientNo",order.getClientNo());
        bodyMap.put("callbackUrl",order.getCallBackUrl());
        bodyMap.put("channelTagId",order.getCategoryId());
        bodyMap.put("phone", order.getPhone());
        bodyMap.put("type", order.getChannelType());
        bodyMap.put("loginKey", order.getLoginKey());
        bodyMap.put("smsCode", smsCode);
        String resultText = HttpClient.doPost(url, baseMap, bodyMap);
        JSONObject object = null;
        try {
            object = JSONObject.parseObject(resultText);
        } catch (Exception e) {
            logger.error("saveIntegralOrderPhoneToThird JSONObject parseObject error");
        }
        Map<String, Object> map = new HashMap<>();
        if (object == null) {
            map.put("operateCode", "09");
            map.put("operateMsg", "系统繁忙");
            return map;
        }
        if (object.containsKey("status")) {
            String status = object.getString("status");
            if (CommonConstants.LEY_RESULT_SUCCESS.equals(status)) {
                String thridResult = object.getString("result");
                String msg = JSONObject.parseObject(thridResult).getString("msg");
                map.put("operateCode", "00");
                map.put("operateMsg", msg);

                order.setSubmitTime(new Date());
                order.setStatus(LoanOrderStatusTypeEnum.TYPE_STATUS_SUBMIT.getKey());
            } else {
                String message = object.getString("message");
                order.setFailureMessage(message);
                order.setStatus(LoanOrderStatusTypeEnum.TYPE_STAUTS_FAILURE.getKey());

                map.put("operateCode", "08");
                map.put("operateMsg", message);
            }
            integralOrderlRepository.saveAndFlush(order);
        }
        return map;
    }

    @Override
    @ApiOperation(value = "验证码报单流程接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "geetestChallenge", value = "第三方验证码1", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "geetestValidate", value = "第三方验证码2", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "geetestSeccode", value = "第三方验证码3", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "orderId", value = "订单标示", dataType = "string", required = true, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/saveIntegralOrderValidateCodeToThird")
    public Map<String, Object> saveIntegralOrderValidateCodeToThird(@RequestParam(value = "geetestChallenge", required=true) String geetestChallenge,
                                                                    @RequestParam(value = "geetestValidate", required=true) String geetestValidate,
                                                                    @RequestParam(value = "geetestSeccode", required=true) String geetestSeccode,
                                                                    @RequestParam(value = "orderId", required=true) Integer orderId) {
        String url = baseHost + "/conversion/open/channel/wemGetsmsByyzm";
        // 生成时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 公钥加密
        String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
        // 建立请求头部数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("X-Auth-OEM", oemID);
        baseMap.put("X-Open-Sign", sign);
        baseMap.put("X-Open-Merchant", merchant);
        baseMap.put("X-Open-Timestamp", timestamp);

        logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步类目价格解析结果=" + RsaUtils.decrypt(privateKey, sign));
        // 建立POST请求
        Optional<TIntegralOrder> option = integralOrderlRepository.findById(orderId);
        TIntegralOrder order = option.isPresent() ? option.get() : null;
        if(order == null) {
            throw new RuntimeException("参数异常");
        }
        Map<String,String> bodyMap = new HashMap<>();
        bodyMap.put("oemChannelId",order.getChannelId());
        bodyMap.put("phone", order.getPhone());
        bodyMap.put("type", order.getChannelType());
        bodyMap.put("geetestChallenge", geetestChallenge);
        bodyMap.put("geetestValidate", geetestValidate);
        bodyMap.put("geetestSeccode", geetestSeccode);

        String resultText = HttpClient.doPost(url, baseMap, bodyMap);
        JSONObject object = null;
        try {
            object = JSONObject.parseObject(resultText);
        } catch (Exception e) {
            logger.error("saveIntegralOrderValidateCodeToThird JSONObject parseObject error");
        }
        Map<String, Object> map = new HashMap<>();
        if (object == null) {
            map.put("operateCode", "09");
            map.put("operateMsg", "系统繁忙");
            return map;
        }
        order.setGeetestSeccode(geetestSeccode);
        order.setGeetestValidate(geetestValidate);
        order.setGeetestChallenge(geetestChallenge);
        if (object.containsKey("status")) {
            String status = object.getString("status");
            if (CommonConstants.LEY_RESULT_SUCCESS.equals(status)) {
                String thridResult = object.getString("result");
//                String msg = JSONObject.parseObject(thridResult).getString("msg");
                String errorMsg = JSONObject.parseObject(thridResult).getString("ErrorMsg");
                String loginKey = JSONObject.parseObject(thridResult).getString("loginKey");
                order.setLoginKey(loginKey);

                map.put("operateCode", "01");
                map.put("operateMsg", "短信报单");
                map.put("orderId", order.getId());
            } else {
                String message = object.getString("message");
                order.setFailureMessage(message);
                order.setStatus(LoanOrderStatusTypeEnum.TYPE_STAUTS_FAILURE.getKey());

                map.put("operateCode", "08");
                map.put("operateMsg", message);
            }
            integralOrderlRepository.saveAndFlush(order);

        }
        return map;
    }

    @Override
    @ApiOperation(value = "获取客服链接")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platformChannelId", value = "平台通道标示", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户标示", dataType = "int", required = true, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getCustomerServiceUrl")
    public String getCustomerServiceUrl(@RequestParam(value = "platformChannelId", required=true) String platformChannelId,
                                        @RequestParam(value = "userId", required=true) Long userId) {
        String url = baseHost + "/conversion/open/channel/getCustomerServiceUrl";
        // 生成时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 公钥加密
        String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
        // 建立请求头部数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("X-Auth-OEM", oemID);
        baseMap.put("X-Open-Sign", sign);
        baseMap.put("X-Open-Merchant", merchant);
        baseMap.put("X-Open-Timestamp", timestamp);

        logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步类目价格解析结果=" + RsaUtils.decrypt(privateKey, sign));
        // 建立POST请求
        Map<String,String> bodyMap = new HashMap<>();
        bodyMap.put("channelId",platformChannelId);
        bodyMap.put("onlyNo", String.valueOf(userId));

        String resultText = HttpClient.doGet(url, baseMap, bodyMap);
        JSONObject object = null;
        try {
            object = JSONObject.parseObject(resultText);
        } catch (Exception e) {
            logger.error("getCustomerServiceUrl JSONObject parseObject error");
        }
        String result = null;
        if (object == null) {
            return result;
        }
        if (object.containsKey("status")) {
            String status = object.getString("status");
            if (CommonConstants.LEY_RESULT_SUCCESS.equals(status)) {
                result = object.getString("result");
            } else {
                result = object.getString("message");
            }
        }
        return result;
    }

    */
/**
     * 短信兑换 PHONE获取验证码接口
     * @param order
     * @return
     *//*

    public Map<String, Object> getSmsCodeFromThird(TIntegralOrder order) {
        {
            String url = baseHost + "/conversion/open/channel/getSmsCode";
            // 生成时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            // 公钥加密
            String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
            // 建立请求头部数据
            Map<String, String> baseMap = new HashMap<>();
            baseMap.put("X-Auth-OEM", oemID);
            baseMap.put("X-Open-Sign", sign);
            baseMap.put("X-Open-Merchant", merchant);
            baseMap.put("X-Open-Timestamp", timestamp);

            logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步类目价格解析结果=" + RsaUtils.decrypt(privateKey, sign));
            // 建立POST请求
            Map<String,String> bodyMap = new HashMap<>();
            bodyMap.put("oemChannelId",order.getChannelId());
            bodyMap.put("clientNo",order.getClientNo());
            bodyMap.put("callbackUrl",order.getCallBackUrl());
            bodyMap.put("channelTagId",order.getCategoryId());
            bodyMap.put("phone", order.getPhone());
            bodyMap.put("type", order.getChannelType());
            String resultText = HttpClient.doPost(url, baseMap, bodyMap);
            JSONObject object = null;
            try {
                object = JSONObject.parseObject(resultText);
            } catch (Exception e) {
                logger.error("getSmsCodeFromThird JSONObject parseObject error");
            }
            Map<String, Object> map = new HashMap<>();
            if (object == null) {
                map.put("operateCode", "09");
                map.put("operateMsg", "系统繁忙");
                return map;
            }
            if (object.containsKey("status")) {
                String status = object.getString("status");
                if (CommonConstants.LEY_RESULT_SUCCESS.equals(status)) {
                    String thridResult = object.getString("result");
                    String ErrorCode = JSONObject.parseObject(thridResult).getString("ErrorCode"); //返回码
                    String ErrorMsg = JSONObject.parseObject(thridResult).getString("ErrorMsg");
                    //报单成功
                    if("000".equals(ErrorCode) && "LoginSuccess".equals(ErrorMsg)) {
                        order.setErrorMsg(ErrorMsg);
                        order.setErrorCode(ErrorCode);
                        order.setStatus(LoanOrderStatusTypeEnum.TYPE_STATUS_SUBMIT.getKey());
                        order.setSubmitTime(new Date());
                        map.put("operateCode", "00");
                        map.put("operateMsg", "提交成功");
                    } else if ("000".equals(ErrorCode) && "GetSmsSuccess".equals(ErrorMsg)) {
                        String loginKey = JSONObject.parseObject(thridResult).getString("loginKey");
                        //短信报单
                        order.setLoginKey(loginKey);
                        order.setErrorMsg(ErrorMsg);
                        order.setErrorCode(ErrorCode);
                        map.put("operateCode", "01");
                        map.put("operateMsg", "短信报单");
                        map.put("orderId", order.getId());
                    } else if("001".equals(ErrorCode)) {
                        //验证码报单
                        String gt = JSONObject.parseObject(thridResult).getString("gt");
                        String challenge = JSONObject.parseObject(thridResult).getString("challenge");
                        order.setErrorMsg(ErrorMsg);
                        order.setErrorCode(ErrorCode);
                        order.setGt(gt);
                        order.setChallenge(challenge);

                        map.put("operateCode", "02");
                        map.put("operateMsg", "验证码报单");
                        map.put("orderId", order.getId());
                        map.put("gt", gt);
                        map.put("challenge", challenge);
                    } else {
                        //报单失败
                        String message = object.getString("message");
                        order.setFailureMessage(message);
                        order.setErrorMsg(ErrorMsg);
                        order.setErrorCode(ErrorCode);
                        order.setStatus(LoanOrderStatusTypeEnum.TYPE_STAUTS_FAILURE.getKey());

                        map.put("operateCode", "08");
                        map.put("operateMsg", message);
                    }
                    integralOrderlRepository.saveAndFlush(order);
                }
            }
            return map;
        }
    }

    @Override
    @ApiOperation(value = "积分报单接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "source", value = "订单来源", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户标示", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "idCard", value = "身份证号", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "channelId", value = "通道标示", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "类目标示", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "categoryName", value = "类目名称", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "content", value = "兑换码", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "fileUrl", value = "图片", dataType = "string", required = false, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/saveIntegralOrderToThird")
    public  Map<String, Object> saveIntegralOrderToThird(@RequestParam(value = "source", required = true) Integer source,
                                           @RequestParam(value = "userId", required = true) Long userId,
                                           @RequestParam(value = "userName", required = true) String userName,
                                           @RequestParam(value = "idCard", required = true) String idCard,
                                           @RequestParam(value = "phone", required = true) String phone,
                                           @RequestParam(value = "channelId", required = true) String channelId,
                                           @RequestParam(value = "categoryId", required = true) String categoryId,
                                           @RequestParam(value = "categoryName", required = true) String categoryName,
                                           @RequestParam(value = "content", required = false) String content,
                                           @RequestParam(value = "fileUrl", required = false) String fileUrl) {
        TIntegralChannel integralChannel = integralChannelRepository.queryTIntegralChannelByChannelId(channelId);
        TUser user = feignUserServiceClient.queryUser(userId);
        TIntegralOrder order = new TIntegralOrder();
        order.setMarketId(integralChannel.getMarketId());
        order.setBrandId(String.valueOf(user.getBrandId()));
        order.setUserId(userId);
        order.setUserName(userName);
        order.setIdCard(idCard);
        order.setPhone(phone);
        order.setChannelId(channelId);
        order.setChannelName(integralChannel.getPlatformProductName());
        String channelType = integralChannel.getPlatformChannelType();
        order.setChannelType(channelType);
        if (channelType.equals(IntegralPictureTypeEnum.TYPE_EXCHANGE_CODE.getKey())) {
            if (StringUtils.isBlank(content)) {
                throw new RuntimeException("该通道类型兑换码，请输入兑换码");
            }
            order.setContent(content);
        } else if (channelType.equals(IntegralPictureTypeEnum.TYPE_QR_CODE.getKey())) {
            throw new RuntimeException("该类型通道尚未开放");
//            if (StringUtils.isBlank(fileUrl)) {
//                throw new RuntimeException("该通道类型图片兑换，请上传兑换图片");
//            }
//            order.setFileUrl(fileUrl);
        } else if (channelType.equals(IntegralPictureTypeEnum.TYPE_VOUCHER_AND_IMG.getKey())) {
            throw new RuntimeException("该类型通道尚未开放");
//            if (StringUtils.isBlank(fileUrl)) {
//                throw new RuntimeException("该通道类型为兑换码及图片，请上传兑换图片");
//            }
//            if (StringUtils.isBlank(content)) {
//                throw new RuntimeException("该通道类型为兑换码及图片，请输入兑换码");
//            }
//            order.setContent(content);
//            order.setFileUrl(fileUrl);
        }else if (channelType.equals(IntegralPictureTypeEnum.TYPE_PAYMENT.getKey())){
            throw new RuntimeException("该类型通道尚未开放");
        }else if (channelType.equals(IntegralPictureTypeEnum.TYPE_PHONE.getKey())){
            throw new RuntimeException("该类型通道尚未开放");
        }
        logger.info("================================兑换图片={}",fileUrl);
        order.setCategoryId(categoryId);
        order.setCategoryName(categoryName);
        order.setClientNo(OrderNoUtil.getBuyOrderNo("I"));
        order.setCallBackUrl(callbackIntegralUrl);
        order.setStatus(LoanOrderStatusTypeEnum.TYPE_STAUTS_INIT.getKey());
        order.setCreateTime(new Date());
        order.setSource(source);

        order = integralOrderlRepository.saveAndFlush(order);
        logger.info("=====================================贴牌Id={},订单编号={},兑换图片={}",order.getBrandId(),order.getClientNo(),order.getFileUrl());

        Map<String, Object> map = new HashMap<>();
        if(!channelType.equals(IntegralPictureTypeEnum.TYPE_PHONE.getKey())) {
            map = saveIntegralOrderToThridWei(order);
            if (channelType.equals(IntegralPictureTypeEnum.TYPE_PAYMENT.getKey()) && "00".equals(map.get("operateCode"))) {
//                throw new RuntimeException("该类型通道尚未开放");
                String path = this.getClass().getResource("/").getPath() + File.separator + new Random().nextInt(10000) + ".jpg";
                QrCodeUtil.orCode(String.valueOf(map.get("orderUrlPath")), path);
                File file = new File(path);
                try {
                    String url = FASTDFS_BASE_URL + uploadService.uploadFile(file);
                    map.put("orderUrlPath", url);
                } catch (Exception e) {
                    logger.error("uploadService error", e);
                } finally {
                    if(file.exists()) {
                        file.delete();
                    }
                }
            }
        } else {
//            throw new RuntimeException("该类型通道尚未开放");
            getSmsCodeFromThird(order);
        }
        return map;
    }

    @Override
    @ApiOperation(value = "旧积分回调接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name="jsonText",value="接收的回调字符串", required = true, dataType="string", paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/integralCallBackOld")
    public boolean integralCallBackOld(@RequestParam(value = "jsonText", required=true) String jsonText) {
        logger.info("====================积分回调开始===================jsonText={}", jsonText);

        JSONObject object = JSONObject.parseObject(jsonText);
        String callbackType = object.getString("callbackType");
        if(!"CALLBACK_SUCCESS".equals(callbackType)) {
            logger.info("====================积分回调失败===================jsonText={}", jsonText);
            //回调类型不成功
            return false;
        }
        //验签
        String timestampColum = object.getString("timestamp");
        String signT = object.getString("sign");//第三方sign
        String timestamp = RsaUtils.decrypt(privateKey, signT);
        if(timestampColum.equals(timestamp)) {
            String clientNo = object.getString("clientNo");
            String userPrice = object.getString("userPrice");
            TIntegralOrder order = integralOrderlRepository.queryIntegralOrderByClientNo(clientNo);
            if(order.getStatus() == LoanOrderStatusTypeEnum.TYPE_STATUS_FINISH.getKey() || order.getStatus() == LoanOrderStatusTypeEnum.TYPE_STATUS_FENRUN.getKey()) {
                logger.info("====================积分回调订单状态已经为终态===================clentNo={}", order.getClientNo());
                return true;
            }
            BigDecimal userPerfitMoney = new BigDecimal(userPrice).divide(new BigDecimal("100"), 2, RoundingMode.FLOOR);
            order.setUserPrice(userPerfitMoney);
            order.setCallback_time(new Date());
            order.setStatus(LoanOrderStatusTypeEnum.TYPE_STATUS_FINISH.getKey());
            integralOrderlRepository.saveAndFlush(order);

            //进行分润操作
            ProfitThreeForm threeForm = new ProfitThreeForm();

            threeForm.setOrderCode(clientNo);
            threeForm.setUserId(order.getUserId());
            threeForm.setAmount(userPerfitMoney.subtract(userPerfitMoney.multiply(new BigDecimal(profitPercent))).setScale(2, BigDecimal.ROUND_HALF_DOWN));
            threeForm.setChannelId(9999);//手动加入id=9999
            threeForm.setBrandId(Integer.valueOf(order.getBrandId().toString()));
            threeForm.setProfitTypeId(6);
//			threeForm.setProfitLevel(0);
            //三级分销开始
            Boolean result = feignProfitTaskServiceClient.processProfitThreeForm(threeForm);
            logger.info("====================积分回调订单状态分润开始===================clentNo={}", order.getClientNo());
            if(result) {
                TIntegralOrder orderFit = integralOrderlRepository.queryIntegralOrderByClientNo(clientNo);
                orderFit.setStatus(LoanOrderStatusTypeEnum.TYPE_STATUS_FENRUN.getKey());
                orderFit.setRebet_time(new Date());
                integralOrderlRepository.saveAndFlush(orderFit);
                logger.info("====================积分回调订单状态分润结束===================clentNo={}", order.getClientNo());
            } else {
                logger.info("====================积分回调订单状态分润失败===================clentNo={}", order.getClientNo());
            }

        } else {
            //验签失败
            logger.info("====================积分回调订单状态验签失败===================jsonText={}", jsonText);
            return false;
        }
        logger.info("====================积分回调结束===================jsonText={}", jsonText);
        return true;
    }

    @Override
    @ApiOperation(value = "积分回调接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name="jsonText",value="接收的回调字符串", required = true, dataType="string", paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/integralCallBack")
    public boolean integralCallBack(@RequestParam(value = "jsonText", required=true) String jsonText) {
        logger.info("====================积分回调开始===================jsonText={}", jsonText);

        JSONObject object = JSONObject.parseObject(jsonText);
        String callbackType = object.getString("callbackType");
        if(!"CALLBACK_SUCCESS".equals(callbackType)) {
            logger.info("====================积分回调失败===================jsonText={}", jsonText);
            //回调类型不成功
            return false;
        }
        //验签
        String timestampColum = object.getString("timestamp");
        String signT = object.getString("sign");//第三方sign
        String timestamp = RsaUtils.decrypt(privateKey, signT);
        if(timestampColum.equals(timestamp)) {
            String clientNo = object.getString("clientNo");
            String userPrice = object.getString("userPrice");
            TIntegralOrder order = integralOrderlRepository.queryIntegralOrderByClientNo(clientNo);
            if(order.getStatus() == LoanOrderStatusTypeEnum.TYPE_STATUS_FINISH.getKey() || order.getStatus() == LoanOrderStatusTypeEnum.TYPE_STATUS_FENRUN.getKey()) {
                logger.info("====================积分回调订单状态已经为终态===================clentNo={}", order.getClientNo());
                return true;
            }
            BigDecimal userPerfitMoney = new BigDecimal(userPrice).divide(new BigDecimal("100"), 2, RoundingMode.FLOOR);
            order.setUserPrice(userPerfitMoney);
            order.setCallback_time(new Date());
            order.setStatus(LoanOrderStatusTypeEnum.TYPE_STATUS_FINISH.getKey());
            integralOrderlRepository.saveAndFlush(order);

            //进行分润操作
            ReturnT result=null;
            String remark = "来自" + order.getPhone().substring(0, 3) + "****" + order.getPhone().substring(order.getPhone().length() - 4, order.getPhone().length());
            try {
                result=feignUserAccountServiceClient.userProfitadd(order.getUserId(), TUserRebateHistoryTypeEnum.INTERGRATION_EXCHANE.getKey(), "0", String.valueOf(userPerfitMoney), clientNo, remark, order.getPhone(), order.getUserId());
                logger.info("=================add profit balance userId={}, realAmount={}, result={}",order.getUserId(), userPerfitMoney, result.getCode() + "--" + result.getMsg() + "-" + result.getData());
            } catch (Exception e) {
                logger.error("user Profit add error", e);
            }
            if(result.getCode() == ReturnT.SUCCESS_CODE) {
                TIntegralOrder orderFit = integralOrderlRepository.queryIntegralOrderByClientNo(clientNo);
                orderFit.setStatus(LoanOrderStatusTypeEnum.TYPE_STATUS_FENRUN.getKey());
                orderFit.setRebet_time(new Date());
                integralOrderlRepository.saveAndFlush(orderFit);
                logger.info("====================积分回调订单状态分润结束===================clentNo={}", order.getClientNo());
            } else {
                logger.info("====================积分回调订单状态分润失败===================clentNo={}", order.getClientNo());
            }

        } else {
            //验签失败
            logger.info("====================积分回调订单状态验签失败===================jsonText={}", jsonText);
            return false;
        }
        logger.info("====================积分回调结束===================jsonText={}", jsonText);
        return true;
    }

    */
/**
     * 保存订单记录
     *//*

    public Map<String, Object> saveIntegralOrderToThridWei(TIntegralOrder order) {
        String url = baseHost + "/conversion/open/channel/save";
        // 生成时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 公钥加密
        String sign = RsaUtils.encrypt(publicKey, String.valueOf(timestamp));
        // 建立请求头部数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("X-Auth-OEM", oemID);
        baseMap.put("X-Open-Sign", sign);
        baseMap.put("X-Open-Merchant", merchant);
        baseMap.put("X-Open-Timestamp", timestamp);

        logger.info("baseMap=" + baseMap.toString() + " url=" + url + " timestamp=" + timestamp + ",sign=" + sign + ",同步类目价格解析结果=" + RsaUtils.decrypt(privateKey, sign));
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("oemChannelId", order.getChannelId());
        bodyMap.put("clientNo", order.getClientNo());
        bodyMap.put("callbackUrl", order.getCallBackUrl());
        String channelType = order.getChannelType();
        bodyMap.put("type", channelType);
        bodyMap.put("channelTagId", order.getCategoryId());
        Map<String, Object> map = new HashMap<>();
        File pdfFile = null;
        try {
            String path = this.getClass().getResource("/").getPath();
            Random rd = new Random();
            if (channelType.equals(IntegralPictureTypeEnum.TYPE_EXCHANGE_CODE.getKey())) {
                if (StringUtils.isBlank(order.getContent())) {
                    throw new RuntimeException("该通道类型兑换码，请输入兑换码");
                }
                bodyMap.put("content", order.getContent());
            } else if (channelType.equals(IntegralPictureTypeEnum.TYPE_QR_CODE.getKey())) {
//                throw new RuntimeException("该类型通道尚未开放");
                if (StringUtils.isBlank(order.getFileUrl())) {
                    throw new RuntimeException("该通道类型图片兑换，请上传兑换图片");
                }
                pdfFile = downLoadByUrl(order.getFileUrl(), rd.nextInt(10000) + ".jpg", path);
            } else if (channelType.equals(IntegralPictureTypeEnum.TYPE_VOUCHER_AND_IMG.getKey())) {
//                throw new RuntimeException("该类型通道尚未开放");
                if (StringUtils.isBlank(order.getFileUrl())) {
                    throw new RuntimeException("该通道类型为兑换码及图片，请上传兑换图片");
                }
                if (StringUtils.isBlank(order.getContent())) {
                    throw new RuntimeException("该通道类型为兑换码及图片，请输入兑换码");
                }
                pdfFile = downLoadByUrl(order.getFileUrl(), rd.nextInt(10000) + ".jpg", path);
                bodyMap.put("content", order.getContent());
            }

            // 建立POST请求
            String resultText = HttpClient.doPost(url, baseMap, bodyMap, pdfFile);
            if(pdfFile != null && pdfFile.exists()) {
                logger.info("====================兑换图片不为null");
                pdfFile.delete();
            }
//            pdfFile.delete();
            logger.info("saveIntegralOrderToThridWei text={}", resultText);
            JSONObject object = null;
            try {
                object = JSONObject.parseObject(resultText);
            } catch (Exception e) {
                logger.error("saveIntegralOrderToThridWei JSONObject parseObject error");
            }
            if (object == null) {
                map.put("operateCode", "09");
                map.put("operateMsg", "系统繁忙");
                return map;
            }
            if (object.containsKey("status")) {
                String status = object.getString("status");
                if (CommonConstants.LEY_RESULT_SUCCESS.equals(status)) {
                    String thridResult = object.getString("result");
                    String customerServiceUrlPath = JSONObject.parseObject(thridResult).getString("customerServiceUrlPath"); //客服二维码
                    String transNo = JSONObject.parseObject(thridResult).getString("transNo");
                    if(channelType.equals(IntegralPictureTypeEnum.TYPE_PAYMENT.getKey())){
//                        throw new RuntimeException("该类型通道尚未开放");
                        String orderUrlPath = JSONObject.parseObject(thridResult).getString("orderUrlPath");
                        order.setOrderUrlPath(orderUrlPath);
                        map.put("orderUrlPath", orderUrlPath);
                    }
                    order.setCustomerServiceUrlPath(customerServiceUrlPath);
                    order.setTransNo(transNo);
                    order.setSubmitTime(new Date());
                    order.setStatus(LoanOrderStatusTypeEnum.TYPE_STATUS_SUBMIT.getKey());
                    map.put("operateCode", "00");
                    map.put("operateMsg", "提交成功");
//                  map.put("orderId", order.getId());
                } else {
                    String message = object.getString("message");
                    order.setStatus(LoanOrderStatusTypeEnum.TYPE_STAUTS_FAILURE.getKey());
                    order.setFailureMessage(message);
                    map.put("operateCode", " 08");
                    map.put("operateMsg", message);
                }
                integralOrderlRepository.saveAndFlush(order);
            }
        } catch (Exception ex) {
            logger.error("saveIntegralOrderToThridWei ex", ex);
        } finally {
            if(pdfFile != null && pdfFile.exists()) {
                pdfFile.delete();
            }
        }
        return map;
    }

    */
/**
     * 从网络Url中下载文件
     *//*

    public File downLoadByUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(5*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }
        logger.info("info:"+url+" download success");
        return file;

    }

    */
/**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     *//*

    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    @Override
    @ApiOperation(value = "获取积分通道接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "platformProductName", value = "通道名称名称(模糊查询)", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "0:未上架 1：已上架", required = false, dataType = "int", paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getIntegralChannelPageList")
    public Page<TIntegralChannel> getIntegralChannelPageList(@RequestParam(value = "pageNum", required = true) Integer pageNum,
                                                             @RequestParam(value = "pageSize", required = true) Integer pageSize,
                                                             @RequestParam(value = "platformProductName", required = false) String platformProductName,
                                                             @RequestParam(value = "status", required = false) Integer status) {
        Specification<TIntegralChannel> specification = new Specification<TIntegralChannel>() {

            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<TIntegralChannel> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (StringUtils.isNoneBlank(platformProductName)) {
                    predicates.add(criteriaBuilder.like(root.get("platformProductName"), "%" + platformProductName + "%"));
                }
                if (status != null) {
                    predicates.add(criteriaBuilder.equal(root.get("status"), status));
                }
//                Predicate pred1=criteriaBuilder.notEqual(root.get("updateUser"), "SYSTEM");
//                Predicate pred2=criteriaBuilder.equal(root.get("updateUser"),null);
//                predicates.add(criteriaBuilder.or(pred1, pred2));
                predicates.add(criteriaBuilder.or(criteriaBuilder.notEqual(root.get("updateUser"), "SYSTEM"), criteriaBuilder.equal(root.get("updateUser"),criteriaBuilder.nullLiteral(String.class))));

                Predicate[] pre = new Predicate[predicates.size()];
//                query.orderBy(criteriaBuilder.asc(root.get("sort")));
                return query.where(predicates.toArray(pre)).getRestriction();
            }
        };
        List<Sort.Order> orders =new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC,"isHot"));
        orders.add(new Sort.Order(Sort.Direction.DESC,"sort"));
        Sort sort = new Sort(orders);
        Pageable pageable = PageRequest.of(pageNum == 0 ? pageNum : pageNum - 1, pageSize,sort);
//        Pageable pageable = new PageRequest(pageNum == 0 ? pageNum : pageNum - 1, pageSize);
        org.springframework.data.domain.Page<TIntegralChannel> page = integralChannelRepository.findAll(specification, pageable);
        pageNum = (pageNum == 0 ? 1 : pageNum);
        Page<TIntegralChannel> localPage = new Page<>(page.getContent(), page.getTotalElements(), pageNum, page.getSize());
        List<TIntegralChannel> list = localPage.getContent();
        for (TIntegralChannel product : list) {
            product.setThridStatusName(WechartStatusTypeEnum.getEnumByKey(product.getThridStatus()).getValue());
            product.setStatusName(ChannelStatusTypeEnum.getEnumByKey(product.getStatus()).getValue());
            product.setPlatformChannelTypeName(IntegralPictureTypeEnum.getEnumByKey(product.getPlatformChannelType()).getValue());
        }
        return localPage;
    }

    @Override
    @ApiOperation(value = "获取订单分页列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "clientNo", value = "订单号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "channelType", value = "通道类型", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户标示", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "brandId", value = "贴牌标示", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "订单状态", required = false, dataType = "int", paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getIntegralOrderPageList")
    public Page<TIntegralOrder> getIntegralOrderPageList(@RequestParam(value = "pageNum", required=true) Integer pageNum,
                                                         @RequestParam(value = "pageSize", required=true)Integer pageSize,
                                                         @RequestParam(value = "clientNo", required=false) String clientNo,
                                                         @RequestParam(value = "phone", required=false) String phone,
                                                         @RequestParam(value = "channelType", required=false) String channelType,
                                                         @RequestParam(value = "userId", required=false) Long userId,
                                                         @RequestParam(value = "brandId", required=false) Long brandId,
                                                         @RequestParam(value = "status", required=false) Integer status) {
        Specification<TIntegralOrder> specification=new Specification<TIntegralOrder>() {

            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<TIntegralOrder> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if(StringUtils.isNoneBlank(clientNo)) {
                    predicates.add(criteriaBuilder.equal(root.get("clientNo"), clientNo));
                }
                if(StringUtils.isNoneBlank(phone)) {
                    predicates.add(criteriaBuilder.equal(root.get("phone"), phone));
                }
                if (StringUtils.isNoneBlank(channelType)) {
                    predicates.add(criteriaBuilder.equal(root.get("channelType"),channelType));
                }
                if(userId != null) {
                    predicates.add(criteriaBuilder.equal(root.get("userId"), userId));
                }
                if (brandId!=null) {
                    predicates.add(criteriaBuilder.equal(root.get("brandId"), brandId));
                }
                if(status != null) {
                    predicates.add(criteriaBuilder.equal(root.get("status"), status));
                }
                Predicate[] pre = new Predicate[predicates.size()];
                query.orderBy(criteriaBuilder.asc(root.get("id")));
                return query.where(predicates.toArray(pre)).getRestriction();
            }
        };
        Pageable pageable = new PageRequest(pageNum == 0 ? pageNum : pageNum - 1, pageSize);
        org.springframework.data.domain.Page<TIntegralOrder> page = integralOrderlRepository.findAll(specification, pageable);
        pageNum = (pageNum == 0 ? 1 : pageNum);
        Page<TIntegralOrder> localPage = new Page<>(page.getContent(), page.getTotalElements(), pageNum, page.getSize());
        List<TIntegralOrder> list= localPage.getContent();
        for(TIntegralOrder order : list) {
            if (StringUtils.isNotBlank(order.getPhone())) {
                order.setPhone(order.getPhone().replace(order.getPhone().substring(3, order.getPhone().length() - 4), "****"));
            }
            if (StringUtils.isNotBlank(order.getIdCard())) {
                order.setIdCard(order.getIdCard().replace(order.getIdCard().substring(1, order.getIdCard().length() - 1), "****************"));
            }
            order.setStatusName(LoanOrderStatusTypeEnum.getEnumByKey(order.getStatus()).getValue());
            order.setChannelTypeName(IntegralPictureTypeEnum.getEnumByKey(order.getChannelType()).getValue());
        }
        return localPage;
    }

    @Override
    @ApiOperation(value = "通过id标示获取积分通道")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键标示id", dataType = "int", required = true, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getIntegralChannelById")
    public TIntegralChannel getIntegralChannelById(@RequestParam(value = "id", required = true) Integer id) {
        Optional<TIntegralChannel> option = integralChannelRepository.findById(id);
        return option.isPresent() ? option.get() : null;
    }

    @Override
    @ApiOperation(value = "通道上下架操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "操作用户标识", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "上下架状态：0：下架 1：上架", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "通道标识", dataType = "int", required = true, paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/updateStatusById")
    public int updateStatusById(@RequestParam(value = "userId", required = true) Integer userId,
                                @RequestParam(value = "id", required = true) Integer id,
                                @RequestParam(value = "status", required = true) Integer status) {

        Optional<TIntegralChannel> channelOption = integralChannelRepository.findById(id);
        if (!channelOption.isPresent()) {
            throw new RuntimeException("参数异常");
        }
        TIntegralChannel channel = channelOption.get();
        if (channel == null) {
            throw new RuntimeException("参数异常");
        }
        if (status != 0 && status != 1) {
            throw new RuntimeException("status参数异常");
        }
        channel.setStatus(status);
        channel.setUpdateUser(String.valueOf(userId));
        integralChannelRepository.saveAndFlush(channel);
        return 1;
    }

    @Override
    @ApiOperation(value = "更新通道接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "操作用户标识", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "通道标识", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "通道排序", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "isHot", value = "是否热门：0：no 1：yes", dataType = "int", paramType = "query")})
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/updateChannelById")
    public int updateChannelById(@RequestParam(value = "userId", required = true) Integer userId,
                                 @RequestParam(value = "id", required = true) Integer id,
                                 @RequestParam(value = "sort", required = false) Integer sort,
                                 @RequestParam(value = "isHot", required = false) Integer isHot) {

        Optional<TIntegralChannel> optional = integralChannelRepository.findById(id);
        TIntegralChannel integralChannel = optional.isPresent() ? optional.get() : null;
        if (integralChannel == null) {
            throw new RuntimeException("参数异常");
        }
        integralChannel.setSort(sort);
        integralChannel.setIsHot(isHot);
        integralChannel.setUpdateUser(String.valueOf(userId));
        integralChannelRepository.saveAndFlush(integralChannel);
        return 1;
    }

    */
/**
     * 获取兑换类型
     * @return
     *//*

    @Override
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/integral/getConversionType")
    public ReturnT getConversionType() {
        List list=new ArrayList();
        for (String s : IntegralPictureTypeEnum.getAllEnum()) {
            IntegralPictureTypeEnum integralPictureTypeEnum=IntegralPictureTypeEnum.getEnumByKey(s);
            Map<String,String> map=new HashMap<>();
            map.put("key",integralPictureTypeEnum.getKey());
            map.put("value",integralPictureTypeEnum.getValue());
            list.add(map);
        }
        return new ReturnT<>(list);
    }
}
*/
